﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data.OleDb;
using System.Data;
using System.IO;

namespace MulticastTV
{
    class ExportToCSV
    {
        public void Start(string file)
        {
            // sort datatable by channel number
            DataView dw = ChannelTable.menu.Tables["Menu"].DefaultView;
            dw.Sort = "Chan";
            StringBuilder strbuild = new StringBuilder();

            strbuild.Append("Channel,Name,Locked,Group,Language,Ip\r\n");
            foreach (DataRowView dr in dw)
            {
                string ip = dr[0].ToString();
                if (ip.Contains(","))
                {
                    ip = @"""" + ip + @"""";
                }
                int ch = (int)dr[1];
                string name = dr[2].ToString();
                if (name.Contains(","))
                {
                    name = name.Replace("\"","");
                    name = @"""" + name + @"""";
                 }
                string audio = dr[4].ToString();
                if (audio.Contains(","))
                {
                    audio = audio.Replace("\"", "");
                    audio = @"""" + audio + @"""";
                }
                string group = dr[3].ToString();
                if (group.Contains(","))
                {
                    group = group.Replace("\"", "");
                    group = @"""" + group + @"""";
                }
                string locked = "0";
                if (locked.Contains(","))
                {
                    locked = locked.Replace("\"", "");
                    locked = @"""" + locked + @"""";
                }

                strbuild.Append(ch.ToString() +"," + name + "," + locked + "," + group + "," + audio + "," + ip+"\r\n");
            }

            StreamWriter sw = File.CreateText(file);
            if (strbuild.Length - 2 > 0)
            {
                strbuild.Remove(strbuild.Length - 2, 2);
            }
            sw.Write(strbuild);
            sw.Close();
        }
    }
}
